<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/15
 * Time: 23:05
 */
namespace app\common\library\task;



use app\common\model\Zbrateconfig;
use app\common\model\zbtask\Money;
use app\common\utils\Utils;
use think\Db;
use think\exception\ValidateException;

class WuhuRateService extends BaseRateService
{

    protected static $noRate = 30000; //每个月免税金额
    public function __construct($options) {
        parent::__construct();
        self::$noRate = $options['noRate'] ?? 30000;
    }

    /**
     * 获取历史众包费
     * 需要加入时间限制 时间限制为当前任务时间之前的已经发送的数据 进行众包费计算
     * @param int $time  当前税率时间   根据这个时间解析出 今年开始时间 税率：开始时间  ==》 当前$time时间
     * @return  object
     */
    public function getOld($time, $where = []) {
        if (!$this->data) {
            throw new ValidateException('请先设置数据');
        }
        $year = date('Y', $time);
        $start = mktime(0, 0, 0, 1, 1, $year);  //今年开始时间
        $old = self::$taskMoney
            ->where(['user_id'=> $this->data['user_id'], 'status'=> 1, 'type' => ['neq', 2]])
            ->where(['createtime'=> ['elt', $time]]) //大于等于，因为相等的时间戳可能同一个人，有好几条数据
            ->where(['createtime'=> ['gt', $start]])
            ->where($where)
            ->sum('money'); //总众包费用 有效 未驳回众包费 如果删除某一条众包费 会导致重新计算

        if(!$old) {
            $old = 0;
        }

        $curRateMoney = $this->getRateMoney($time); // 'rateMoney' => $rateMoney, 'noRate' => $noRate,

        $this->data['curRateMoney'] = $curRateMoney;
        $this->old = Utils::processMoney($old, $curRateMoney['noRate'], '+');

        return $this;
    }


    //获取真正的数据
    public function process() {
        $res = $this->sureRes;
        $data = [];
        if ($this->data['money_type'] == 1) {
            $res['get_money'] = Utils::processMoney($this->data['money'], $res['allTaxMoney'], '-', 2);
            $res['money'] = $this->data['money'];
            $res['ca_money'] = Utils::processMoney($this->data['curRateMoney']['rateMoney'], config('site.money_tax_radio'), '*', 2);
        } else {
            $res['get_money'] = $this->data['money']; //实发
            $res['money'] = Utils::processMoney($this->data['money'], $res['allTaxMoney'], '+', 2);
            $res['ca_money'] = Utils::processMoney($res['money'], config('site.money_tax_radio'), '*', 2);
        }

        $this->sureRes = $res;
        return $res;
    }
    /**
     * 根据应发金额，推算实发金额
     * @param array $oldDetail detail方法测算结果
     * @return array $moneyDetail
     */
    public function taxMoney($oldDetail) {
        //纳税金额 应纳税所得额
        $new = Utils::processMoney($this->data['curRateMoney']['rateMoney'], self:: $radio, '*', 6);
        $moneyDetail = [];
        //不纳税部分生成方式
        if ($new == 0) {
            //都不需要纳税
            $origin = $this->norate($this->data['money']);
            array_push($moneyDetail, $origin['detail']);

            return $moneyDetail;
        } else {
            //把不纳税部分单独生成一条数据
            $noratemoney = $this->data['curRateMoney']['noRate'];
            if ($noratemoney) {
                $origin = $this->norate($noratemoney);
                array_push($moneyDetail, $origin['detail']);
            }
        }
        //由小到大 排好的顺序$all += Utils::processMoney($money, $v['tax_rate'], '*');
        foreach (self::$config as $k => $v) {
            if ($new <= 0) {
                break;
            }
            if ($k < $oldDetail['index']) {
                continue;
            }
            //相等的时候扣除
            if ($k == $oldDetail['index']) { //等于老的比较特殊单独处理
                //大于剩余 或者小于剩余
                if ($new <= $oldDetail['remain']) {
                    $temp = $this->tempArr($new, $v['tax_rate'], $v['kouchushu']);
                    array_push($moneyDetail, $temp);
                    return $moneyDetail;
                } else {
                    if ($oldDetail['remain'] == 0) {continue;};
                    $temp = $this->tempArr($oldDetail['remain'], $v['tax_rate'], $v['kouchushu']);
                    array_push($moneyDetail, $temp);
                    $new = Utils::processMoney($new, $oldDetail['remain'], '-', 6);
                }
            } else {
                if($new <= $v['tax_money']) {
                    $temp = $this->tempArr($new, $v['tax_rate'], $v['kouchushu']);
                    array_push($moneyDetail, $temp);
                    return $moneyDetail;
                } else {
                    $temp = $this->tempArr($v['tax_money'], $v['tax_rate'], $v['kouchushu']);
                    $new = Utils::processMoney($new, $v['tax_money'], '-', 6);
                    array_push($moneyDetail, $temp);
                }
            }
        }

        return $moneyDetail; //要缴纳的税款
    }

    public function norate($money) {
        $ca_money = Utils::processMoney($money, self::$radio, '*', 8);
        $temp = $this->tempArr($ca_money, 0, 0);

        return [
            'originMoney' => $money,//应发
            'detail' => $temp
        ];
    }
    /*
  * 通过实发推导 应发
  * $new 为实发金额 是扣除税的金额
  * $oldDetail 为历史记录
  * */
    public function taxRealMoney($oldDetail) {
        //1：全部不纳税：应税收入为全部，2：部分纳税：， 3：全部纳税，
        $realRemain = $this->calculateReal($oldDetail['remain'], $oldDetail['config']);  //当前段位实发 其中可能包含 不纳税额部分
        $new = $this->data['curRateMoney']['rateMoney'];  //应纳税额部分
        $moneyDetail = [];            //计算数组
        //不纳税部分生成方式
        if ($new == 0) {
            //都不需要纳税
            $origin = $this->norate($this->data['money']);
            array_push($moneyDetail, $origin['detail']);

            return $moneyDetail;
        } else {
            //把不纳税部分单独生成一条数据
            $noratemoney = $this->data['curRateMoney']['noRate'];
            if ($noratemoney) {
                $origin = $this->norate($noratemoney);
                array_push($moneyDetail, $origin['detail']);
            }
        }
        if ($realRemain >= $new) {
            $origin = $this->calculateOrigin($new, $oldDetail['config']);  //重新计算ca_money 值为应发金额*10%
            array_push($moneyDetail, $origin['detail']);
            return $moneyDetail;
        } else {
            //如果本段剩余 不为0 需要计算
            if ($realRemain > 0) {
                $new = Utils::processMoney($new, $realRemain, '-', 8);  //剩余实发
                //重新计算ca_money 值为应发金额*10%   不纳税金额的norate * 10% + 纳税额的ca_money
                $origin = $this->calculateOrigin($realRemain, $oldDetail['config']);  //不纳税
                array_push($moneyDetail, $origin['detail']);
            }
            foreach (self::$config as $k => $v) {
                if ($k > $oldDetail['index']) {
                    //本段位实发总额
                    $realRemain = $this->calculateReal($v['tax_money'], $v);
                    if ($realRemain >= $new) {
                        $origin = $this->calculateOrigin($new, $v);
                        array_push($moneyDetail, $origin['detail']);
                        break;
                    } else {
                        $origin = $this->calculateOrigin($realRemain, $v);
                        array_push($moneyDetail, $origin['detail']);
                        $new = Utils::processMoney($new, $realRemain, '-', 6);
                    }

                }
            }

            return $moneyDetail;
        }
    }
    /**
     * 因为3万一下金额免费，所以在这个地方把免费的金额加入到累计纳税金额当中，用来计算应纳税部分的税率
     * 计算当月累计发送金额 按照任务创建时间
     * @return array
     */
    public function getRateMoney($time) {
        if (!$this->data) {
            throw new ValidateException('请先设置数据');
        }
        //计算当月累计发送金额 按照任务创建时间
        $start = date('Y-m-01',$time); //月初
        $end = date('Y-m-d 11:59:59', strtotime("$start +1 month -1 day"));//月末

        $where['createtime'] = ['between time', [$start, $end]];
        $where['status'] = 1;
        $where['type'] = ['neq', 2];
        $where['user_id'] = $this->data['user_id'];
        //本月累计已发
        $month = self::$taskMoney->where($where)->sum('money');
        $money = $this->data['money'];
        $noRate = self::$noRate;

        $remain = Utils::processMoney($noRate, $month, '-'); //剩余不纳税金额
        if ($remain <= 0) {
            //当前金额，全部纳税
            $rateMoney = $money;   //应纳税额部分
            $noRate = 0;           //不纳税额部分
        } else {
            //当大于0的时候 ，有一部分不纳税
            if ($remain >= $money) {
                //一份的都不纳税
                $rateMoney = 0; //应纳税额部分
                $noRate = $money; //不纳税额部分
            } else {
                $rateMoney = Utils::processMoney($money, $remain, '-'); //应纳税额的部分
                $noRate = $remain;//不纳税额部分
            }
        }

        return [
            'rateMoney' => $rateMoney,
            'noRate' => $noRate,
        ];
    }
}